# cython: language_level=3
import app.model_phl.my_tool_package as my_package
import utils
import app.utils.util_log as util_log
import datetime


def get_is_rule_featues(freatures, key):
    if 'none' == freatures.get(key, 'none') or freatures.get(key, 'none') is None:
        util_log.get_logger().warning('get_is_rule_featues {} error'.format(key))
        return False
    else:
        return True


class WhiteRules(object):
    """
    白名单新客规则
    """

    def __int__(self):
        pass

    def initial_abtest(self, free_features):
        """
        abtest分流
        :param free_features:
        :return:
        """
        pass

    # 一 拒绝策略模块
    # 1.1 普通拒绝策略
    # 1）准入规则
    # 2）反欺诈规则
    # 3）黑名单规则
    # 4）多头规则

    def __ordinary_rule__(self, free_features):
        """
        白名单新客策略
        编码原则：
        1 开头： 准入规则
        2 开头： 欺诈规则
        3 开头： 黑名单规则
        4 开头： 信用规则
        5 开头：信用评分规则
        6 开头 临时规则
        :param free_features:
        :return:
        """
        # 梳理新客的规则
        rule_sets_result = {}

        # 准入规则
        if get_is_rule_featues(free_features, 'age') and (
                (int(free_features['age']) > 0 and int(free_features['age'] < 18)) or int(free_features[
            'age'] > 65)):
            rule_sets_result['m101'] = 1
        if get_is_rule_featues(free_features, 'on_loan_not_yet_cnt') and int(free_features['on_loan_not_yet_cnt']) > 0:
            rule_sets_result['m102'] = 1

        # 欺诈规则
        # if get_is_rule_featues(free_features, 'con_contact_cnt') and free_features['con_contact_cnt'] >= 10:
        #     rule_sets_result['m201'] = 1

        if get_is_rule_featues(free_features, 'biz_devRegCnt_1w') and int(free_features['biz_devRegCnt_1w']) >= 10:
            rule_sets_result['m202'] = 1

        if get_is_rule_featues(free_features, 'biz_devRegCnt_1d') and int(free_features['biz_devRegCnt_1d']) >= 10:
            rule_sets_result['m203'] = 1

        if get_is_rule_featues(free_features, 'biz_gpsRegCnt_1d') and int(free_features['biz_gpsRegCnt_1d']) >= 10:
            rule_sets_result['m204'] = 1

        if get_is_rule_featues(free_features, 'biz_ipRegCnt_1d') and int(free_features['biz_ipRegCnt_1d']) >= 10:
            rule_sets_result['m205'] = 1

        if get_is_rule_featues(free_features, 'biz_fbid_cnt') and int(free_features['biz_fbid_cnt']) >= 5:
            rule_sets_result['m206'] = 1

        if get_is_rule_featues(free_features, 'bankcard_associated_phone_cnt') and int(free_features['bankcard_associated_phone_cnt']) >= 10:
            rule_sets_result['m207'] = 1

        if get_is_rule_featues(free_features, 'con_contact_fraudlevel1_cnt') and int(free_features['con_contact_fraudlevel1_cnt']) >= 999:
            rule_sets_result['m208'] = 1

        if get_is_rule_featues(free_features, 'major_phone_majorfraud_cnt') and int(free_features['major_phone_majorfraud_cnt']) >= 999:
            rule_sets_result['m209'] = 1

        # 3 黑名单
        if get_is_rule_featues(free_features, 'inner_black_phone') and int(free_features['inner_black_phone']) == 1:
            rule_sets_result['m301'] = 1

        if get_is_rule_featues(free_features, 'inner_black_idCard') and int(free_features['inner_black_idCard']) == 1:
            rule_sets_result['m302'] = 1

        if get_is_rule_featues(free_features, 'inner_black_macCode') and int(free_features['inner_black_macCode']) == 1:
            rule_sets_result['m303'] = 1

        if get_is_rule_featues(free_features, 'inner_black_gaid') and int(free_features['inner_black_gaid']) == 1:
            rule_sets_result['m304'] = 1

        if get_is_rule_featues(free_features, 'inner_black_ip') and int(free_features['inner_black_ip']) == 1:
            rule_sets_result['m305'] = 1

        if get_is_rule_featues(free_features, 'inner_black_gps') and int(free_features['inner_black_gps']) == 1:
            rule_sets_result['m306'] = 1

        if get_is_rule_featues(free_features, 'overdue_sms_cnt') and int(free_features['overdue_sms_cnt']) > 90:
            rule_sets_result['m307'] = 1

        if get_is_rule_featues(free_features, 'is_gongzhai_overdue_order') and int(free_features['is_gongzhai_overdue_order']) == 1:
            rule_sets_result['m308'] = 1

        if get_is_rule_featues(free_features, 'outer_black_blurry_namebirthday') and int(free_features['outer_black_blurry_namebirthday']) == 1:
            rule_sets_result['m309'] = 1

        if get_is_rule_featues(free_features, 'outer_black_blurry_idcard') and int(free_features['outer_black_blurry_idcard']) == 1:
            rule_sets_result['m310'] = 1


        # 其他策略集
        if get_is_rule_featues(free_features, 'biz_black_GidDevice')  and int(free_features['biz_black_GidDevice']) > 0:
            rule_sets_result['m401'] = 1

        if get_is_rule_featues(free_features, 'LAST_refuse001') and int(free_features['LAST_refuse001']) >= 31:
            rule_sets_result['m402'] = 1

        if get_is_rule_featues(free_features, 'app_riskLoanAppCnt') and int(free_features['app_riskLoanAppCnt']) > 0:
            rule_sets_result['m403'] = 1

        if get_is_rule_featues(free_features, 'app_loan_maxDays') and int(free_features['app_loan_maxDays']) >= 999:
            rule_sets_result['m404'] = 1

        if get_is_rule_featues(free_features, 'biz_max_expire_day_all_real_idcard_history') and int(free_features['biz_max_expire_day_all_real_idcard_history']) > 2:
            rule_sets_result['m405'] = 1

        if get_is_rule_featues(free_features, 'biz_max_expire_day_all_phone_history') and int(free_features['biz_max_expire_day_all_phone_history']) > 2:
            rule_sets_result['m406'] = 1

        if get_is_rule_featues(free_features, 'app_loan_medianDays') and int(free_features['app_loan_medianDays']) >= 999:
            rule_sets_result['m407'] = 1

        if get_is_rule_featues(free_features, 'biz_devLoanCnt') and int(free_features['biz_devLoanCnt']) == 1:
            rule_sets_result['m408'] = 1

        if get_is_rule_featues(free_features, 'biz_maxDpd') and int(free_features['biz_maxDpd']) > 2:
            rule_sets_result['m409'] = 1

        if get_is_rule_featues(free_features, 'biz_curDefault') and int(free_features['biz_curDefault']) > 0:
            rule_sets_result['m410'] = 1

        if get_is_rule_featues(free_features, 'biz_lastOrderDpd') and int(free_features['biz_lastOrderDpd']) > 2:
            rule_sets_result['m411'] = 1

        if get_is_rule_featues(free_features, 'app_inst_d3_cnt') and int(free_features['app_inst_d3_cnt']) >= 31:
            rule_sets_result['m412'] = 1

        if get_is_rule_featues(free_features, 'whitelist_first_time_diff_days') and int(free_features['whitelist_first_time_diff_days']) >= 9999:
            rule_sets_result['m413'] = 1

        # 20240823修改策略阈值
        if int(free_features.get('ProjectId', 0)) == 10077:
            if get_is_rule_featues(free_features, 'white_list_jiange_days') and int(free_features['white_list_jiange_days']) > 40:
                rule_sets_result['m414'] = 1
        
        if int(free_features.get('ProjectId', 0)) in ([10041, 10042, 10070, 10086]):
            if get_is_rule_featues(free_features, 'white_list_jiange_days') and int(free_features['white_list_jiange_days']) > 40:
                rule_sets_result['m414'] = 1
        
        # 20240709
        # # 新客新增拒绝策略
        # if get_is_rule_featues(free_features, 'biz_all_phone_sour_cnt_7d') and int(free_features['biz_all_phone_sour_cnt_7d']) >= 2:
        #     rule_sets_result['m105'] = 1

        # 20240809 m105编码规则修改
        # 20240904 m105编码规则修改
        if get_is_rule_featues(free_features, 'biz_all_phone_sour_cnt_7d') and int(free_features['biz_all_phone_sour_cnt_7d']) >= 2:
            if int(free_features.get('ProjectId', 0)) in ([10077, 10086, 10041, 10042]):
                #  if get_is_rule_featues(free_features, 'FinPower_Score_V2') and int(free_features['FinPower_Score_V2']) <= 530:
                #     rule_sets_result['m105'] = 1

                 if get_is_rule_featues(free_features, 'XWWhitListScoreV2') and int(float(free_features['XWWhitListScoreV2'])) <= 540:
                    rule_sets_result['m105'] = 1
            # if int(free_features.get('ProjectId', 0)) in ([10041, 10042]):
            #      if get_is_rule_featues(free_features, 'FinPower_Score_V4') and int(free_features['FinPower_Score_V4']) <= 530:
            #         rule_sets_result['m105'] = 1
  
        # 20240809 增加m113规则
        if get_is_rule_featues(free_features, 'biz_userid_pendingloan_cnt') and int(free_features['biz_userid_pendingloan_cnt']) >= 2:
            rule_sets_result['m113'] = 1

        # 20240709
        # 针对EasyLoan新客和新增的线下包主产品新客
        # if int(free_features.get('ProjectId', 0)) in ([10041, 10086]):
        #     if get_is_rule_featues(free_features, 'biz_all_phone_shouyi_amt') and int(free_features['biz_all_phone_shouyi_amt']) < 0:
        #         rule_sets_result['m106'] = 1




        # 20240717
        # 增加在贷未还笔数的逻辑
        # biz_all_userid_norepay_cnt > 3
        if get_is_rule_featues(free_features, 'biz_all_userid_norepay_cnt') and int(free_features['biz_all_userid_norepay_cnt']) > 3:
                rule_sets_result['m107'] = 1

        # 20240814新客规则集
        if get_is_rule_featues(free_features, 'max_overdue_days') and free_features[
            'max_overdue_days'] > 2:
            rule_sets_result['m419'] = 1

        if get_is_rule_featues(free_features, 'biz_max_expire_day_all_phone_cur') and free_features[
            'biz_max_expire_day_all_phone_cur'] > 0:
            rule_sets_result['m420'] = 1

        if get_is_rule_featues(free_features, 'biz_max_expire_day_all_real_idcard_cur') and free_features[
            'biz_max_expire_day_all_real_idcard_cur'] > 0:
            rule_sets_result['m421'] = 1
        
        return rule_sets_result
    

        

    # 1.2 信用评分拒绝策略
    def __score_rule__(self, free_features):
        """
        信用分规则
        :param free_features:
        :return:
        """
        rule_sets_result = {}

        # 信用评分规则
        # Easy Loan产品
        # 20240821
        # Easy Loan产品拦截尾量
        # if int(free_features.get('ProjectId', 0)) == 10041:
        #     if get_is_rule_featues(free_features, 'FinPower_Score_V4') and int(free_features['FinPower_Score_V4']) <= 505:
        #         rule_sets_result['m507'] = 1

        # FastService产品 10077
        # 20240709
        # 新增线下包 
        # 20240821
        # QuickDelivery拦截尾量
        # 主产品 10086	Quick Delivery
        # if int(free_features.get('ProjectId', 0)) in ([10086]):
        #     if get_is_rule_featues(free_features, 'FinPower_Score_V2') and int(free_features['FinPower_Score_V2']) <= 505:
        #         rule_sets_result['m507'] = 1

        # 20240821 EasyLoan产品和QuickDelivery产品新客采用阿伟模型新客V1版本，做主模型
        # 20240904 FS增加使用主模型
        if int(free_features.get('ProjectId', 0)) in ([10041]):
            if get_is_rule_featues(free_features, 'XWWhitListScoreV2') and int(float(free_features['XWWhitListScoreV2'])) <= 520:
                rule_sets_result['m501'] = 1

        if int(free_features.get('ProjectId', 0)) in ([10077]):
            if get_is_rule_featues(free_features, 'XWWhitListScoreV2') and int(float(free_features['XWWhitListScoreV2'])) <= 535:
                rule_sets_result['m501'] = 1

        if int(free_features.get('ProjectId', 0)) in ([10086]):
            if get_is_rule_featues(free_features, 'XWWhitListScoreV2') and int(float(free_features['XWWhitListScoreV2'])) <= 530:
                rule_sets_result['m501'] = 1


        # FastService新客评分拒绝阈值修改为520（20240809）
        # 20240904 FS使用阿伟新客评分V2版本拒绝
        # if int(free_features.get('ProjectId', 0)) in ([10077, 10086]):
        #     if get_is_rule_featues(free_features, 'XWWhitListScoreV2') and int(float(free_features['XWWhitListScoreV2'])) <= 515:
        #         rule_sets_result['m501'] = 1

        # Future cash产品
        if int(free_features.get('ProjectId', 0)) == 10070:
            if get_is_rule_featues(free_features, 'CreditScoreV4') and int(free_features['CreditScoreV4']) <= 521:
                rule_sets_result['m501'] = 1

        #  Lucky Cash产品
        # 20240904 LC主产品使用阿伟新客评分V2版本
        if int(free_features.get('ProjectId', 0)) == 10042:
            if get_is_rule_featues(free_features, 'XWWhitListScoreV2') and int(float(free_features['XWWhitListScoreV2'])) <= 515:
                rule_sets_result['m501'] = 1

        # 所有产品增加自研评分新客V4版本拒绝策略
        # 20240814QD调整自研评分V4的拒绝阈值
        if int(free_features.get('ProjectId', 0)) in ([10086, 10042]):
            if get_is_rule_featues(free_features, 'CreditScoreV4') and int(free_features['CreditScoreV4']) > 0 and int(free_features['CreditScoreV4']) <= 516:
                rule_sets_result['m503'] = 1
        elif int(free_features.get('ProjectId', 0)) in ([10077]):
            if get_is_rule_featues(free_features, 'CreditScoreV4') and int(free_features['CreditScoreV4']) > 0 and int(free_features['CreditScoreV4']) <= 505:
                rule_sets_result['m503'] = 1
        else:
            if get_is_rule_featues(free_features, 'CreditScoreV4') and int(free_features['CreditScoreV4']) > 0 and int(free_features['CreditScoreV4']) <= 500:
                rule_sets_result['m503'] = 1

        #20240809
        #所有新客主产品的用阿维新客评分做拒绝策略
        # 1）FS和QD产品
        if int(free_features.get('ProjectId', 0)) in ([10077]):
            if get_is_rule_featues(free_features, 'XingWeiRisk') and float(free_features['XingWeiRisk']) <= 480:
                    rule_sets_result['m504'] = 1

        # 2）EL和LC产品
        if int(free_features.get('ProjectId', 0)) in ([10042]):
            if get_is_rule_featues(free_features, 'XingWeiRisk') and float(free_features['XingWeiRisk']) <= 490:
                    rule_sets_result['m504'] = 1

        # 3）QD/EL产品
        if int(free_features.get('ProjectId', 0)) in ([10086, 10041]):
            if get_is_rule_featues(free_features, 'XingWeiRisk') and float(free_features['XingWeiRisk']) <= 500:
                    rule_sets_result['m504'] = 1


        # 20240914FS新增卫总评分V4的策略
        if int(free_features.get('ProjectId', 0)) == 10077:
            if get_is_rule_featues(free_features, 'FinPower_Score_V4') and int(free_features['FinPower_Score_V4']) <= 505:
                rule_sets_result['m507'] = 1

        return rule_sets_result

    # 1.3 拒绝策略集成
    def rules(self, free_features):
        """
        白名单新客规则
        :param free_features:
        :return:
        """
        rule_sets_result = {}
        rule_result = self.__ordinary_rule__(free_features=free_features)
        rule_sets_result.update(rule_result)
        score_result = self.__score_rule__(free_features=free_features)
        rule_sets_result.update(score_result)
        return rule_sets_result

    # 差异化额度
    def __get_branch_id__(self, free_features):
        # 利用评分做差异化额度配置

        creditScore = free_features.get('FinPower_Score_V2', 0)
        if creditScore == None:
            creditScore = 0
        
        if creditScore <= 525:
            return 1
        elif creditScore <= 536:
            return 2
        else:
            return 3

    def __get_branch_id_v1__(self, free_features):

        creditScoreV4 = free_features.get('CreditScoreV4', 0)
        if creditScoreV4== None:
            creditScoreV4 = 0

        if creditScoreV4 <= 530:
            return 1
        elif creditScoreV4 <= 538:
            return 2
        elif creditScoreV4 <= 555:
            return 3
        else:
            return 4

    def __get_branch_id_v2__(self, free_features):

        creditScore = free_features.get('FinPower_Score_V4', 0)
        if creditScore == None:
            creditScore = 0

        if creditScore <= 520:
            return 1
        elif creditScore <= 530:
            return 2
        elif creditScore <= 540:
            return 3
        else:
            return 4



    def __preloan_amount__(self, free_features, FraudAssessmentResults):
        """
        额度策略
        :param free_features:
        :param FraudAssessmentResults:
        :return:
        """
        amount = 0

        if FraudAssessmentResults == 'reject':
            return amount

        ProjectId = int(free_features.get('ProjectId', 0))
        
        score = free_features.get('FinPower_Score_V4', 0)
        if score == None:
            score = 0

        score1 = free_features.get('FinPower_Score_V2', 0)
        if score1 == None:
            score1 = 0

        score2 = int(float(free_features.get('XWWhitListScoreV2', 0)))

        # 说明：
        # ProjectID的编号与产品对应的关系
        # 1）10041 Easy Loan
        # 2）10070 Future cash
        # 3) 10042 LuckyCash
        # 4) 10077 Fast Service

        # Easy Loan新客差异化额度
        # if ProjectId == 10041:
        #     if score <= 521:
        #         amount = 2000
        #     elif score <= 529:
        #         amount = 2500
        #     elif score <= 539:
        #         amount = 4000
        #     else:
        #         amount = 5000

        # 20240821 EasyLoan新客差异化额度
        if ProjectId == 10041:
            if score2 <= 530:
                amount = 2000
            elif score2 <= 545:
                amount = 2500
            elif score2 <= 560:
                amount = 3500
            else:
                amount = 5000

        # 20240904 主产品授信额度策略
        # 1) LuckyCash 主产品新客
        if ProjectId == 10042:
            if score2 <= 530:
                amount = 2000
            elif score2 <= 545:
                amount = 3000
            elif score2 <= 560:
                amount = 4000
            else:
                amount = 5000


        # Fast Service主产品固定化额度 3000
        # 20240625
        # 20240628 差异化额度
        # 20240708 差异化额度，额度提升
        # if ProjectId == 10077:
        #     if score1 <= 545:
        #         amount = 2000
        #     elif score1 <= 560:
        #         amount = 4000
        #     else:
        #         amount = 5000


        # 20240709 Quick Delivery 主产品差异化额度
        # if ProjectId == 10086:
        #     if score1 <= 545:
        #         amount = 2000
        #     elif score1 <= 560:
        #         amount = 3000
        #     else:
        #         amount = 5000

        # 20240821 QuickDelivery 主产品差异化额度
        if ProjectId in ([10086, 10077]):
            if score2 <= 530:
                amount = 1500
            elif score2 <= 545:
                amount = 2000
            elif score2 <= 560:
                amount = 3000
            elif score2 <= 590:
                amount = 4000
            else:
                amount = 5000
            
        # Future Cash新客差异化额度  
        if ProjectId == 10070:
            branch_id_1 = self.__get_branch_id_v1__(free_features)

            if branch_id_1 == 1:
                amount = 1500
            elif branch_id_1 == 2:
                amount = 2000
            elif branch_id_1 == 3:
                amount = 4000
            else:
                amount = 5000

        # Lucky Cash新客差异化额度
        # if ProjectId == 10042:
        #     branch_id_2 = self.__get_branch_id_v2__(free_features)

        #     if branch_id_2 == 1:
        #         amount = 2000
        #     elif branch_id_2 == 2:
        #         amount = 3000
        #     elif branch_id_2 == 3:
        #         amount = 4000
        #     else:
        #         amount = 5000

        biz_all_phone_sour_cnt_7d = free_features.get('biz_all_phone_sour_cnt_7d', 0)
        biz_all_phone_shouyi_amt = free_features.get('biz_all_phone_shouyi_amt', 0)

        if  biz_all_phone_sour_cnt_7d is None:
            pass 
        elif biz_all_phone_sour_cnt_7d >= 2:
            amount = 1500
        
        if biz_all_phone_shouyi_amt is None:
            pass 
        elif biz_all_phone_shouyi_amt < 0:
            amount = 1500

        return amount

    # 二 额度策略模块
    # 贷前授信额度
    def preloan_amount(self, free_features, FraudAssessmentResults):
        """
        白名单新客额度
        :param free_features:
        :param FraudAssessmentResults:
        :return:
        """
        return self.__preloan_amount__(free_features=free_features, FraudAssessmentResults=FraudAssessmentResults)